package com.ww.editsms.widget;

import java.util.List;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.chinawangw.R;


public class SearchAdapter extends SimpleAdapter {

	private List<Map<String, String>> data;
	Context context;
	PopupWindow popupWindow;
	SearchEditText s;
	public SearchAdapter(Context context, List<Map<String, String>> data,
			int resource, String[] from, int[] to,PopupWindow popupWindow,SearchEditText s) {
		super(context, data, resource, from, to);
		this.data = data;
		this.context = context;
		this.popupWindow = popupWindow;
		this.s = s;
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView,
			ViewGroup parent) {
		System.out.println(position);
		ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = LayoutInflater.from(context).inflate(
					R.layout.core_search_pw_item, null);
			holder.btn = (ImageButton) convertView
					.findViewById(R.id.delete);
			holder.tv = (TextView) convertView.findViewById(R.id.item);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.tv.setText(data.get(position).get("text").toString());
		
		holder.tv.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				s.setText(data.get(position).get("text").toString());
				if (popupWindow != null) {
					popupWindow.dismiss();
				}
			}
		});
		
		holder.btn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SearchDBHelper s = new SearchDBHelper(context);
				boolean b=s.delete(context.getPackageName(), data.get(position).get("text").toString());
				if(b){
					data.remove(position);
					notifyDataSetChanged();
				}
			}
		});
		return convertView;
	}
	
	
	class ViewHolder {
		private TextView tv;
		private ImageButton btn;
	}
}
